<template>
  <div class="app-container">
    <header class="app-header">
      <div class="header-content">
        <div class="logo">
          <img src="/ai-assistant.svg" alt="AI Assistant" width="24" height="24" />
          <span>AI 智能助手</span>
        </div>
      </div>
    </header>
    
    <main class="main-content">
      <div class="message-area-wrapper">
        <ResultsDisplay 
          :search-results="searchResults"
          :ai-answer="aiAnswer"
          class="message-area"
          @suggestion-click="handleSuggestionClick"
        />
      </div>
      
      <div class="input-area">
        <SearchInput
          ref="searchInputRef"
          v-model:selected-model="selectedModel"
          @search-start="handleSearchStart"
          @search-success="handleSearchSuccess"
          @search-error="handleSearchError"
        />
      </div>
      
    </main>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import SearchInput from './components/SearchInput.vue';
import ResultsDisplay from './components/ResultsDisplay.vue';

const searchInputRef = ref(null);
const searchResults = ref([]);
const aiAnswer = ref('');
const isLoadingAI = ref(false);
const selectedModel = ref('openai'); // 默认使用 OpenAI

const handleSearchStart = () => {
  searchResults.value = [];
  aiAnswer.value = '';
};

const handleSearchSuccess = async (results, query) => {
  searchResults.value = results;
  console.log('搜索结果:', results);
  
  try {
    isLoadingAI.value = true;
    console.log('开始请求AI回答...');
    
    const requestBody = {
      userQuery: query,
      webContent: results.map(r => r.snippet).join('\n')
    };
    console.log('请求数据:', requestBody);
    
    // 根据选择的模型使用不同的接口
    const endpoint = selectedModel.value === 'openai' 
      ? 'http://localhost:3000/api/generate'
      : 'http://localhost:3000/api/generate-ollama';
    
    const response = await fetch(endpoint, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(requestBody)
    });
    
    console.log('API响应状态:', response.status);
    
    if (!response.ok) {
      throw new Error(`AI服务响应错误: ${response.status} ${response.statusText}`);
    }
    
    const data = await response.json();
    console.log('AI回答数据:', data);
    
    if (data && data.answer) {
      aiAnswer.value = data.answer;
      console.log('AI回答已设置:', aiAnswer.value.substring(0, 50) + '...');
    } else {
      console.error('API返回数据格式不正确:', data);
      aiAnswer.value = 'AI服务返回格式不正确';
    }
  } catch (error) {
    console.error('AI回答生成失败:', error);
    aiAnswer.value = `AI服务暂时不可用: ${error.message}`;
  } finally {
    isLoadingAI.value = false;
  }
};

const handleSearchError = (error) => {
  console.error('搜索流程错误:', error);
};

const handleSuggestionClick = (suggestion) => {
  if (searchInputRef.value) {
    searchInputRef.value.setSearchQuery(suggestion);
    searchInputRef.value.triggerSearch();
  }
};
</script>

<style>
.app-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background: #f8f9fa;
}

.app-header {
  background: white;
  border-bottom: 1px solid #eaecef;
  padding: 12px 0;
}

.header-content {
  max-width: 800px;
  margin: 0 auto;
  padding: 0 16px;
  display: flex;
  align-items: center;
}

.logo {
  display: flex;
  align-items: center;
  gap: 8px;
}

.logo span {
  font-size: 16px;
  font-weight: 600;
  color: #1a1a1a;
}

.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  position: relative;
}

.message-area-wrapper {
  flex: 1;
  overflow: auto;
  padding-bottom: 100px;
}

.input-area {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  box-shadow: 0 -2px 10px rgba(0,0,0,0.05);
  z-index: 50;
}

.loading-indicator {
  position: fixed;
  bottom: 100px;
  left: 50%;
  transform: translateX(-50%);
  background: rgba(0,0,0,0.7);
  color: white;
  padding: 8px 16px;
  border-radius: 20px;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 8px;
  z-index: 40;
}

.loading-dots {
  display: flex;
  gap: 4px;
}

.loading-dots span {
  width: 6px;
  height: 6px;
  background: white;
  border-radius: 50%;
  animation: dot-flashing 1s infinite linear alternate;
}

.loading-dots span:nth-child(2) {
  animation-delay: 0.2s;
}

.loading-dots span:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes dot-flashing {
  0% {
    opacity: 0.2;
  }
  100% {
    opacity: 1;
  }
}

@media (max-width: 768px) {
  .header-content {
    padding: 0 12px;
  }
  
  .message-area-wrapper {
    padding-bottom: 80px;
  }
}
</style>
